package com.basic.business.order.server;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.basic.business.common.utils.StringUtils;
import com.basic.business.order.domain.TOrdersDetail;
import com.basic.business.order.domain.TOrdersMain;
import com.basic.business.order.domain.TOrdersMerge;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 解析结果
 *
 * @author zhaoxy_jn@163.com
 */
@Slf4j
@Component
public class ParseOrders {

    /**
     * 解析返回结果
     * @param timeRange 时间范围
     * @param jsonResult 快麦返回的结果
     */
    public List<TOrdersMain> parseOrders(String[] timeRange, JSONObject jsonResult) {
        List<TOrdersMain> ordersMainList = new ArrayList<>();
        try {
            // 获取订单列表
            JSONArray jsonResults = jsonResult.getJSONArray("list");
            if (jsonResults == null || jsonResults.isEmpty()) {
                log.warn("{}, 订单为空", Arrays.toString(timeRange));
                return Collections.emptyList();
            }

            for (int i = 0; i < jsonResults.size(); i++) {
                JSONObject order = jsonResults.getJSONObject(i);

                // 主订单信息
                TOrdersMain ordersMain = order.toJavaObject(TOrdersMain.class);

                // 获取子订单信息
                JSONArray orders = order.getJSONArray("orders");
                if (orders != null) {
                    for (int j = 0; j < orders.size(); j++) {
                        JSONObject orderResult = orders.getJSONObject(j);
                        TOrdersDetail ordersDetail = orderResult.toJavaObject(TOrdersDetail.class);
                        ordersDetail.setMainSid(ordersMain.getSid());
                        // 如果订单标题为空，则取sysTitle字段
                        if (Objects.isNull(ordersDetail.getTitle())) {
                            ordersDetail.setTitle(orderResult.getString("sysTitle"));
                        }
                        // 是否赠品 Y是 N否 若giftNum赠品数量>0，则是赠品，否则不是赠品
                        ordersDetail.setIsGift(orderResult.getInteger("giftNum") > 0 ? "Y" : "N");
                        ordersMain.getDetailList().add(ordersDetail);

                        // 若子订单只有一条，则直接将主订单备注给子订单
                        if(orders.size() == 1) {
                            ordersDetail.setSellerMemo(ordersMain.getSellerMemo());
                        }
                    }
                }

                // 获取订单消息备忘录
                JSONArray messageMemos = order.getJSONArray("messageMemos");
                if (messageMemos != null) {
                    for (int j = 0; j < messageMemos.size(); j++) {
                        JSONObject messageMemo = messageMemos.getJSONObject(j);
                        TOrdersMerge ordersMerge = messageMemo.toJavaObject(TOrdersMerge.class);
                        ordersMerge.setMainSid(ordersMain.getSid());
                        ordersMain.getMergeList().add(ordersMerge);
                        // 系统订单号
                        long sid = ordersMerge.getMergeSid();
                        // 卖家备注
                        String sellerMemo = ordersMerge.getSellerMemo();
                        if (StringUtils.isNotNull(sellerMemo)) {
                            // 将卖家备注设置到子订单中
                            for (TOrdersDetail ordersDetail : ordersMain.getDetailList()) {
                                if (Objects.equals(ordersDetail.getDetailSid(), sid)) {
                                    ordersDetail.setSellerMemo(sellerMemo);
                                    break;
                                }
                            }
                        }
                    }
                }

                // 获取标签
                JSONArray tradeTags = order.getJSONArray("tradeTags");
                if (tradeTags != null) {
                    String tags = null;
                    for (int j = 0; j < tradeTags.size(); j++) {
                        JSONObject tag = tradeTags.getJSONObject(j);
                        String tagId = tag.getString("id");
                        // 多个标签用逗号分隔
                        if (StringUtils.isNotNull(tags)) {
                            tags += "," + tagId;
                        } else {
                            tags = tagId;
                        }
                    }
                    ordersMain.setTags(tags);
                }

                ordersMainList.add(ordersMain);
            }
        } catch (Exception e) {
            log.error("解析订单结果异常: {}, 时间范围: {}", e.getMessage(), Arrays.toString(timeRange), e);
            throw new RuntimeException("解析订单结果失败", e);
        }
        return ordersMainList;
    }
}
